public class SingleLinkedList {
    private Node head; // 链表的第一个节点（无头结点）

    public SingleLinkedList() {
        this.head = null;
    }

    // 头插法
    public void addFirst(int data) {
        Node newNode = new Node(data);
        newNode.next = head;
        head = newNode;
    }

    // 尾插法
    public void addLast(int data) {
        Node newNode = new Node(data);
        if (head == null) {
            head = newNode;
        } else {
            Node current = head;
            while (current.next != null) {
                current = current.next;
            }
            current.next = newNode;
        }
    }

    // 任意位置插入, 第一个数据节点为0号下标
    public boolean addIndex(int index, int data) {
        if (index < 0 || index > size()) {
            return false;
        }
        if (index == 0) {
            addFirst(data);
            return true;
        }
        Node newNode = new Node(data);
        Node current = head;
        for (int i = 0; i < index - 1; i++) {
            current = current.next;
        }
        newNode.next = current.next;
        current.next = newNode;
        return true;
    }

    // 查找是否包含关键字key是否在单链表当中
    public boolean contains(int key) {
        Node current = head;
        while (current != null) {
            if (current.data == key) {
                return true;
            }
            current = current.next;
        }
        return false;
    }

    // 删除第一次出现关键字为key的节点
    public void remove(int key) {
        if (head == null) return;

        if (head.data == key) {
            head = head.next;
            return;
        }

        Node current = head;
        while (current.next != null && current.next.data != key) {
            current = current.next;
        }
        if (current.next != null) {
            current.next = current.next.next;
        }
    }

    // 删除所有值为key的节点
    public void removeAllKey(int key) {
        Node dummy = new Node(0); // 创建一个虚拟头结点
        dummy.next = head;
        Node prev = dummy;
        Node current = head;

        while (current != null) {
            if (current.data == key) {
                prev.next = current.next;
            } else {
                prev = current;
            }
            current = current.next;
        }
        head = dummy.next;
    }

    // 得到单链表的长度
    public int size() {
        int count = 0;
        Node current = head;
        while (current != null) {
            count++;
            current = current.next;
        }
        return count;
    }

    // 显示链表内容
    public void display() {
        Node current = head;
        while (current != null) {
            System.out.print(current.data + " ");
            current = current.next;
        }
        System.out.println();
    }

    // 清空链表
    public void clear() {
        head = null;
    }
}